package com.dinstar.linphone.utils;

import android.content.Context;
import android.os.Environment;
import android.webkit.MimeTypeMap;

import org.linphone.core.Address;

import java.io.File;
import java.util.Locale;

public class FileUtils {
    public static final String VFS_PLAIN_FILE_EXTENSION = ".bctbx_evfs_plain";

    public static String getDisplayName(Address address) {
        return (!address.getDisplayName().trim().isEmpty())? address.getUsername() : "";
    }


    public static File getFileStoragePath(Context context, String fileName) {
        File path = getFileStorageDir(context, isExtensionImage(fileName));
        File file = new File(path, fileName);

        int prefix = 1;
        while (file.exists()) {
            file = new File(path, prefix + "_" + fileName);
            prefix += 1;
        }
        return file;
    }

    public static File getFileStorageDir(Context context, Boolean isPicture) {
        File path = null;
        if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
            String directory = Environment.DIRECTORY_DOWNLOADS;
            if (isPicture) {
                directory = Environment.DIRECTORY_PICTURES;
            }
            path = context.getExternalFilesDir(directory);
        }

        File returnPath = (path != null)? path: context.getFilesDir();

        return returnPath;
    }

    public static Boolean isExtensionImage(String path) {
        String extension = getExtensionFromFileName(path).toLowerCase(Locale.getDefault());
        String type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
        return (type != null) && type.startsWith("image/") ? true : false;
    }

    public static String getExtensionFromFileName(String fileName) {
        String realFileName = "";
        if (fileName.endsWith(VFS_PLAIN_FILE_EXTENSION)) {
            realFileName = fileName.substring(0, fileName.length() - VFS_PLAIN_FILE_EXTENSION.length());
        } else {
            realFileName = fileName;
        }

        String extension = MimeTypeMap.getFileExtensionFromUrl(realFileName);
        if (extension != null && !extension.isEmpty()) {
            int i = realFileName.lastIndexOf('.');
            if (i > 0) {
                extension = realFileName.substring(i + 1);
            }
        }

        return extension;
    }
}
